<template>
  <div class="xiaobu-container" v-closeSelect="'window'">
    <el-form
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      class="search-form clearfix"
    >
      <el-form-item
        class="search-field fl five-per-row"
        label="名称"
        prop="roleName"
      >
        <el-select
            v-model="queryParams.name"
            filterable
            remote
            placeholder="请输入关键词"
            @focus="remoteMethod('')"
            @change="handlleChange"
            @visible-change="handleVisibleChange"
            :remote-method="remoteMethod"
            :loading="loading">
            <el-option
              v-for="item in options"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleName">
            </el-option>
          </el-select>
      </el-form-item>

      <el-form-item class="fr">
        <el-button type="primary" @click="handleQuery">查 询</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { roleApi } from "@/api"
export default {
  data() {
    return {
      queryParams: {
        name: ""
      },
      options: [], // 下拉选项数据
      loading: false,
      selectPathName: "", // 选中的数据
      selectKey: "" // 搜索关键字
    }
  },
  methods: {
    handlleChange(val) {
      this.selectPathName = val
    },
    handleVisibleChange(val) {
      // 关闭选项卡时
      if (!val) {
        // 判断 name有没有变，有变说明有选择 没变说明没选择 没变 且 有搜索关键字时 设置关键字为搜索条件
        setTimeout(() => {
          if ((!this.queryParams.name || this.queryParams.name === this.selectPathName) && this.selectKey) {
            // 设置后得把 选中值改为 selectKey
            this.selectPathName = this.selectKey
            this.$set(this.queryParams, "name", this.selectKey)
          }
        }, 0)
      }
    },
    remoteMethod(query) {
      // 记录搜索关键字
      this.selectKey = query
      this.loading = true
      const params = {
        roleName: query,
        pageNum: 1,
        pageSize: 50
      }
      roleApi.getList(params).then(res => {
        this.options = res.rows
        this.loading = false
      }).catch(err => {
        this.options = []
        this.loading = false
      })
    },
    handleQuery() {
      setTimeout(() => {
        alert("搜索名称为：" + this.queryParams.name)
      }, 0)
    }
  }
}
</script>
